<?php

/*************
 *    Main   *
 *************/

$debug = true;

// Configuration
$adminRoot          = realpath('..');
$dirRoot            = $adminRoot . "/skin/backend/js/Serum";
$moduleDir          = $adminRoot . "/skin/backend/modules/";
$compressedFile     = $dirRoot . "/Serum.min.js";
$jsFilesToCompress  = array();

// Get recursivly files from dir
getDirFiles($jsFilesToCompress, $dirRoot, array('.js', '.js.php'));
getDirFiles($jsFilesToCompress, $moduleDir, array('.js', '.js.php'));

// Delete the file
@unlink($compressedFile);

$fs = @fopen($compressedFile, 'w');

//@fwrite($fs, "<?php require_once '". $adminRoot ."/app/Main.php'; umask(0); Main::run('admin', null); 

// Compression
foreach ($jsFilesToCompress as $file) {
    //echo '+ ' . $file . "\n" ;
    $exec = '';

	@fwrite($fs, @file_get_contents($file));
	
    /*if (!$debug) {
       $exec .= 'java -jar yuicompressor-2.4.2.jar --charset UTF-8 ';
    } else {
       $exec .= 'cat ';
    }*/

    /*$exec .= $file . ' >> ' . $compressedFile;
    exec($exec);*/
}

@fclose($fs);

//echo ' added in ' . $compressedFile . "\n";

/*************
 * Functions *
 *************/

// Get recursivly files of the directory
function getDirFiles (&$jsFilesToCompress, $dir, $extensions = array()) {
    $excludedDir        = array('.', '..', '.svn');
    
    if (is_dir($dir) && !in_array($dir, $excludedDir)) {
        if ($dh = opendir($dir)) {

            $recursiveDirs = array();

            // Loops files in dir
            while (($file = readdir($dh)) !== false) {

                if (is_dir($dir . '/' . $file) && !in_array($file, $excludedDir)) {

                    // It is a directory containing files
                    $recursiveDirs[]   = $dir . '/' . $file;

                } elseif (!is_dir($file)) {

                    // It is a file
                    $currentExtension   = substr($file, strpos($file, '.'));
                    if ((count($extensions) == 0)
                        ||
                        (in_array($currentExtension, $extensions))
                        ) {
                            // The file is added if no extension is specified or if the extension matches
                            $jsFilesToCompress[] = $dir . '/' . $file;
                    }
                }
            }

            foreach ($recursiveDirs as $recusiveDir){
                getDirFiles($jsFilesToCompress, $recusiveDir, $extensions);
            }
            closedir($dh);
        }
    }
}